package com.ruoyi.project.erp.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.erp.domain.Project;
import com.ruoyi.project.erp.domain.Task;
import com.ruoyi.project.erp.domain.Worklog;
import com.ruoyi.project.erp.dto.WorkLogApprovalDto;
import com.ruoyi.project.erp.dto.WorklogApprovalQuery;
import com.ruoyi.project.erp.mapper.ProjectMapper;
import com.ruoyi.project.erp.mapper.TaskMapper;
import com.ruoyi.project.erp.mapper.WorklogMapper;
import com.ruoyi.project.erp.vo.MyWorkLogApprovalVo;
import com.ruoyi.project.erp.vo.WorklogApprovalVO;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.erp.mapper.WorklogApprovalMapper;
import com.ruoyi.project.erp.domain.WorklogApproval;
import com.ruoyi.project.erp.service.IWorklogApprovalService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工时审批流Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-19
 */
@Service
@Slf4j
public class WorklogApprovalServiceImpl implements IWorklogApprovalService {
    @Autowired
    private WorklogApprovalMapper worklogApprovalMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private WorklogMapper worklogMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询工时审批流
     *
     * @param id 工时审批流主键
     * @return 工时审批流
     */
    @Override
    public WorklogApproval selectWorklogApprovalById(Long id) {
        return worklogApprovalMapper.selectWorklogApprovalById(id);
    }

    /**
     * 查询工时审批流列表
     *
     * @param worklogApproval 工时审批流
     * @return 工时审批流
     */
    @Override
    public List<WorklogApproval> selectWorklogApprovalList(WorklogApproval worklogApproval) {
        return worklogApprovalMapper.selectWorklogApprovalList(worklogApproval);
    }

    /**
     * 新增工时审批流
     *
     * @param worklogApproval 工时审批流
     * @return 结果
     */
    @Override
    public int insertWorklogApproval(WorklogApproval worklogApproval) {
        worklogApproval.setCreateTime(DateUtils.getNowDate());
        return worklogApprovalMapper.insertWorklogApproval(worklogApproval);
    }

    /**
     * 修改工时审批流
     *
     * @param worklogApproval 工时审批流
     * @return 结果
     */
    @Override
    public int updateWorklogApproval(WorklogApproval worklogApproval) {
        return worklogApprovalMapper.updateWorklogApproval(worklogApproval);
    }

    /**
     * 批量删除工时审批流
     *
     * @param ids 需要删除的工时审批流主键
     * @return 结果
     */
    @Override
    public int deleteWorklogApprovalByIds(Long[] ids) {
        return worklogApprovalMapper.deleteWorklogApprovalByIds(ids);
    }

    /**
     * 删除工时审批流信息
     *
     * @param id 工时审批流主键
     * @return 结果
     */
    @Override
    public int deleteWorklogApprovalById(Long id) {
        return worklogApprovalMapper.deleteWorklogApprovalById(id);
    }

    @Override
    @Transactional
    public int workLogApproval(WorkLogApprovalDto dto) {
        log.info("打印入参："+dto);
        // 根据ID查询审批流
        WorklogApproval approval = worklogApprovalMapper.selectWorklogApprovalById(dto.getId());
        // 查询工时记录
        Worklog worklog = worklogMapper.selectWorklogById(approval.getWorklogId());
        // 查询项目
        Project project = projectMapper.selectProjectInfoByProjectId(worklog.getProjectId());
        if ("approved".equals(dto.getStatus())) {
            if (approval.getStep()==2L){
                worklog.setFinalStatus("archived");
                worklog.setStatus("archived");
                approval.setStatus("approved");
                // 修改公式状态
                worklogMapper.updateWorklog(worklog);
                // 修改审批流状态
                approval.setApproveTime(DateUtils.getNowDate());
                worklogApprovalMapper.updateWorklogApproval(approval);
                // 新增销售审批流记录
                approval.setStep(2L);
                approval.setApproverId(project.getSaleId());
                approval.setApproveRemark(dto.getApproveRemark());
                approval.setApproveTime(DateUtils.getNowDate());
                approval.setWorklogId(worklog.getId());
                int i = worklogApprovalMapper.updateWorklogApproval(approval);
            }else {
                if (project.getProjectLeader().equals(project.getSaleId())){
                    approval.setApproveTime(DateUtils.getNowDate());
                    approval.setApproveRemark(dto.getApproveRemark());
                    approval.setStatus("approved");
                    worklogApprovalMapper.updateWorklogApproval(approval);
                    worklog.setFinalStatus("archived");
                    worklog.setStatus("archived");
                    approval.setStatus("approved");
                    // 修改公式状态
                    worklogMapper.updateWorklog(worklog);
                    // 修改审批流状态
                    // 新增销售审批流记录
                    approval.setStep(2L);
                    approval.setApproverId(project.getSaleId());
                    approval.setApproveRemark("");
                    approval.setApproveTime(DateUtils.getNowDate());
                    approval.setWorklogId(worklog.getId());
                    int i = worklogApprovalMapper.insertWorklogApproval(approval);
                }
                approval.setApproveTime(DateUtils.getNowDate());
                approval.setApproveRemark(dto.getApproveRemark());
                approval.setStatus("approved");
                worklogApprovalMapper.updateWorklogApproval(approval);
                worklog.setFinalStatus("pending");
                worklog.setStatus("pending");
                approval.setStatus("pending");
                // 修改公式状态
                worklogMapper.updateWorklog(worklog);
                // 修改审批流状态
                // 新增销售审批流记录
                approval.setStep(2L);
                approval.setApproverId(project.getSaleId());
                approval.setApproveRemark("");
                approval.setApproveTime(DateUtils.getNowDate());
                approval.setWorklogId(worklog.getId());
                int i = worklogApprovalMapper.insertWorklogApproval(approval);
            }


        } else if ("returned".equals(dto.getStatus())) {
            worklogApprovalMapper.deleteWorklogApprovalById(approval.getId());
            worklog.setFinalStatus("returned");
            worklog.setStatus("returned");
            worklogMapper.updateWorklog(worklog);
        } else if ("rejected".equals(dto.getStatus())) {
            if (approval.getStep() == 2L) {
                worklog.setFinalStatus("rejected");
                worklog.setStatus("rejected");
                worklogMapper.updateWorklog(worklog);
                // 修改上一层审批流状态
                WorklogApproval old =  worklogApprovalMapper.selectWorklogByWorkIdAndStep(approval.getWorklogId(),1L);
                old.setStatus("rejected");
                worklogApprovalMapper.updateWorklogApproval(old);
                approval.setStatus("rejected");
                approval.setApproveRemark(dto.getApproveRemark());
                approval.setApproveTime(DateUtils.getNowDate());
                worklogApprovalMapper.updateWorklogApproval(approval);
            } else {
                worklog.setFinalStatus("rejected");
                worklog.setStatus("rejected");
                approval.setApproveRemark(dto.getApproveRemark());
                approval.setStatus("rejected");
                worklogMapper.updateWorklog(worklog);
                worklogApprovalMapper.updateWorklogApproval(approval);
            }
        }
        return 1;
    }

    @Override
    public List<MyWorkLogApprovalVo> queryMyApprovalList() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        List<WorklogApproval> list = worklogApprovalMapper.selectWorklogApprovalByApproverId(loginUser.getUser().getDdUserId());

        if (list == null && list.size() <= 0)
            return new ArrayList<>();

        List<MyWorkLogApprovalVo> collect = list.stream().map(x -> {
            MyWorkLogApprovalVo vos = new MyWorkLogApprovalVo();
            vos.setWorklogApprovalId(x.getId());
            // 查询工时记录
            Worklog worklog = worklogMapper.selectWorklogById(x.getWorklogId());
            BeanUtils.copyProperties(worklog, vos);
            vos.setFinalStatus(x.getStatus());
            Task task = taskMapper.selectTaskById(worklog.getTaskId());
            vos.setTaskName(task.getTaskName());
            vos.setTaskId(task.getId());
            // 查询项目
            Project project = projectMapper.selectProjectInfoByProjectId(task.getProjectId());
            vos.setProjectName(project.getProjectName());
            vos.setProjectId(project.getProjectId());
            //提交人username
            SysUser sysUser = userMapper.selectUserByDdUserId(worklog.getUserId());
            vos.setUserName(sysUser.getNickName());
            return vos;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 查询工时审批列表
     *
     * @param query 工时审批查询条件
     * @return 工时审批集合
     */
    @Override
    // ★★★ 方法名已修改 ★★★
    public List<WorklogApprovalVO> selectList(WorklogApprovalQuery query)
    {
        // ★★★ 调用Mapper的方法名也已修改 ★★★
        return worklogApprovalMapper.selectList(query);
    }
}
